package com.milling.common.utils;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketClient {

    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    private ExecutorService executorService;

    public SocketClient(String host, int port) {
        try {
            // 创建Socket连接
            socket = new Socket(host, port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            // 创建线程池用于异步接收消息
            executorService = Executors.newSingleThreadExecutor();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送消息并异步接收响应
     *
     * @param message 要发送的消息
     */
    public void sendMessageAsync(String message) {
        // 发送消息
        out.println(message);
        System.out.println("Sent: " + message);

        // 异步接收响应
        executorService.submit(() -> {
            try {
                String response = in.readLine();
                if (response != null) {
                    System.out.println("Received: " + response);
                    // 在这里处理服务器返回的信息
                    processResponse(response);
                } else {
                    System.out.println("[WARN] 对方已关闭连接，无数据可读取");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 处理服务器返回的信息
     *
     * @param response 服务器返回的信息
     */
    private void processResponse(String response) {
        // 在这里添加处理逻辑
        System.out.println("Processing response: " + response);
        // 其他逻辑处理
    }

    /**
     * 关闭连接
     */
    public void close() {
        try {
            if (in != null) in.close();
            if (out != null) out.close();
            if (socket != null) socket.close();
            if (executorService != null) executorService.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SocketClient client = new SocketClient("192.168.237.66", 2001);

        // 发送消息并异步接收响应
        client.sendMessageAsync("start");

        // 保持主线程运行，等待异步任务完成
        try {
            Thread.sleep(5000); // 增加等待时间，确保异步任务完成
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 关闭连接
        client.close();
    }
}
